#include<iostream>
using namespace std;
#include<pthread.h>
#include<vector>
#include<unistd.h>
#include<string.h>
#define NUM 5  //创建多个执行流， NUM为执行流个数

using namespace std;

int* p = nullptr;
__thread int g_val = 0;
__thread int number;

//线程的数据信息。 
struct threadData
{
    string threadname;
};

string toHex(pthread_t tid)
{
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);

    return buffer;
}

void InitthreadData(threadData* td, int number)
{
    td->threadname = "thread-" + to_string(number);
}

//新线程的执行代码
void* threadRuntine(void* args)
{
    pthread_detach(pthread_self());
    
    //
    threadData* td = static_cast<threadData*>(args);
    
    number = pthread_self();
    int i = 0;
    while (i < 5)
    {
        cout << "pid: " << getpid() << ", tid: " 
            << toHex(number) << ", name: " 
            << td->threadname
            << ", g_val: " << g_val 
             << ", &g_val: " << &g_val << endl;

        i++;

        g_val++;
        sleep(2);
    }
    delete td;
    return nullptr;
}


int main()
{   
    vector<pthread_t> tids;
    //我们创建多个执行流， 为了能够验证每个线程都有一个独立的栈结构
    for (int i = 0; i < NUM; i++)
    {
        threadData* td = new threadData();
        pthread_t tid;
        InitthreadData(td, i);
        pthread_create(&tid, nullptr, threadRuntine, td);
        tids.push_back(tid);
        usleep(1000);
    }
    //
    // for (auto e : tids)
    // {
    //     pthread_detach(e);
    // }

    for (int i = 0; i < tids.size(); i++)
    {
        int n = pthread_join(tids[i], nullptr);
        cout << "n = " << n << ", who: " << toHex(tids[i]) 
           << ", " << strerror(n) << endl;
    }
    return 0;
}